from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from goods.models import SKU
from decimal import Decimal
from .serializers import OrderPlaceSerializer, OrderSettlementSerializer
from rest_framework.response import Response

class OrderSettlementView(APIView):
    """
    订单结算
    """
    serializer_class = OrderPlaceSerializer
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        """
        获取redis中需要结算的商品
        """
        user = request.user

        # 从购物车中获取用户勾选要结算的商品信息
        redis_conn = get_redis_connection('cart')
        cart_dict = redis_conn.hgetall('cart_%s' % user.id)
        cart_selected_list = redis_conn.smembers('cart_selected_%s' % user.id)

        #2,拼接数据
        sku_list = []
        for sku_id in cart_selected_list:
            sku = SKU.objects.get(id = sku_id)
            sku.count = cart_dict[sku_id]
            sku_list.append(sku)

        #3,获取序列化器
        serializer = self.get_serializer(instance=sku_list,many=True)
        #4,返回响应
        context = {
            "sku":serializer.data,
            "freight":Decimal(10.0)
        }
        return Response(context)